package com.petecat.interchan;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.petecat.interchan.base.project.entity.CpuTime;
import com.petecat.interchan.base.project.entity.EsSofts;
import com.petecat.interchan.base.warning.config.entity.WarningEmpl;
import com.petecat.interchan.es.EsDaoInter;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsQuerySoftwareInfo {
	@Autowired
	private EsDaoInter esDao;
	
	
	/**
	 * 查询ES软件信息
	 */
	@Test
	public void queryEsSoftwareInfo() {
		TransportClient client = esDao.getClient();
		SearchResponse actionGet = client.prepareSearch("monitor-software")
														.addSort("body.sendTime", SortOrder.DESC)
														.setSize(1)
														.execute()
														.actionGet();
		SearchHits hits = actionGet.getHits();
		EsSofts soft = null;
		JSONObject next = null;
		List<EsSofts> softsList = new ArrayList<>();
		try {
			if(hits.totalHits > 0) {
				for (SearchHit searchHit : hits.getHits()) {
					String sourceAsString = searchHit.getSourceAsString();
					JSONObject jsonObject = JSON.parseObject(sourceAsString).getJSONObject("body");
					JSONArray jsonArray = jsonObject.getJSONArray("softs");
					Iterator<Object> iterator = jsonArray.iterator();
					while (iterator.hasNext()) {
						next =  (JSONObject)iterator.next();
						soft = new EsSofts();
						soft.setCreateTime(next.getString("create_time"));
						soft.setMemoryPercent(next.getString("memory_percent"));
						soft.setCpuTimes(JSONObject.parseObject(next.getJSONObject("cpu_times").toString(), CpuTime.class));
						soft.setName(next.getString("name"));
						soft.setNumThreads(next.getString("num_threads"));
						soft.setPid(next.getString("pid"));
						soft.setUserName(next.getString("username"));
						soft.setStatus(next.getString("status"));
						softsList.add(soft);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (client != null) {
				esDao.resume(client);
			}
		}
		
		
	}
}
